package logic

import (
	"context"
	"fmt"
	"tieba/models/cache"
	"tieba/models/mysql"

	"tieba/tiebarpc/internal/svc"
	"tieba/tiebarpc/tiebarpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *tiebarpc.LoginRequest) (*tiebarpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		user.Mobile = in.Mobile
		user.UserName = in.UserName
		user.Password = in.Password
		mysql.DB.Debug().Create(&user)
	}
	get, _ := cache.Rdb.Get(cache.Ctx, "send"+in.Mobile).Result()
	if get != in.SendCode {
		return nil, fmt.Errorf("验证码错误")
	}
	return &tiebarpc.LoginResponse{UserId: int64(user.ID)}, nil
}
